package eu.winterwheels.enterprise.controller.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Logger;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

@ManagedBean
@ApplicationScoped
public class Version {
	@Inject
	private Logger log;
	
	private String webLayerVersion = null;
	private String webLayerTitle = null;
	private String webLayerVendor = null;	

	private Manifest getManifestFile() {
		File manifestFile = null;
		String home = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
		Manifest manifest = null;
		manifestFile = new File(home, "META-INF/MANIFEST.MF");
		try {
			manifest = new Manifest(new FileInputStream(manifestFile));
		} catch (FileNotFoundException fnfe) {
			log.warning("Fail " + manifestFile.getAbsolutePath() + "is not avaialable " + fnfe);			
		} catch (IOException ioe) {
			log.warning("Failed to read from " + manifestFile.getAbsolutePath()
					+ "in order to read the web layer version. " + ioe);
		}
		return manifest;
	}
	
	private String getMetaInfAttribute(String attr){
		Manifest manifest = getManifestFile();
		String attrValue = null;
		if (manifest != null) {
			Attributes attrs = manifest.getMainAttributes();
			attrValue = attrs.getValue(attr);
		}
		return attrValue;
	}

	public synchronized String getWebLayerVersion() {
		webLayerVersion = getMetaInfAttribute("Specification-Version");
		if(webLayerVersion == null)
			webLayerVersion = "";
		return webLayerVersion;
	}

	public synchronized String getWebLayerTitle() {
		webLayerTitle = getMetaInfAttribute("Specification-Title");
		if(webLayerTitle == null)
			webLayerTitle = "";
		return webLayerTitle;
	}

	public synchronized String getWebLayerVendor() {
		webLayerVendor = getMetaInfAttribute("Specification-Vendor");
		if(webLayerVendor == null)
			webLayerVendor = "";
		return webLayerVendor;
	}
}